<?php

namespace app\api\controller;

use app\facade\Redis;
use think\Validate;
use app\models\{Region, Cate, Product, Config, Alipay, Wechat, Wechat2, Annous, Riderlist, RiderStreet, Douyin, Promo, AgentArea, Agent, Car, Payment, Baoming};
use think\facade\Env;
use think\Db;
use oss\Oss;
use think\facade\Log;
use think\db\Where;
use EasyWeChat\Factory;


class Other extends Base
{

    public function gettclist()
    {
        $agentid  = $this->request->get('agentid/d', '0');
        if (empty($agentid)) {
            $this->result([], 0, '获取成功');
        }
        $list = (new Promo())->where(['agentid' => $agentid, 'status' => 1, 'type' => 1])->field('id,title,money,contents')->select();
        foreach ($list as $lists) {
            $title = (new Agent())->where('id', $agentid)->value('title') ?? '';
            if (!empty($title)) {
                $lists['title'] = '[' . $title . ']' . $lists['title'];
            }
            $lists['money'] = (float)$lists['money'];
        }
        $this->result($list, 0, '获取成功');
    }

    public function getcar()
    {
        $lon  = $this->request->get('lon/f', '0');
        $lat  = $this->request->get('lat/f', '0');
        $type  = $this->request->get('type/d', '0');
        $filed = 'ROUND(6378.138*2*ASIN(SQRT(POW(SIN((' . $lat . '*PI()/180-lat*PI()/180)/2),2)+COS(' . $lat . '*PI()/180)*COS(lat*PI()/180)*POW(SIN((' . $lon . '*PI()/180-lon*PI()/180)/2),2)))*100)/100 AS dist';
        $result = (new Agent())
            ->field('id,title as nickname,yytimes,lat,lon,address,' . $filed)
            ->order('dist asc');
        $result = $result->limit(5)->where('id', '>', 1)->where('istrue',2)->select();
        foreach ($result as $results) {
            $results['product'] =  (new Product())
                ->where(['isdel' => 1, 'isshow' => 1, 'agentid' => $results['id']])
                ->field('id,title,images,price,price1,price2,descs,iskey')->select();
            $results['images'] = $results['product'][0]['images'] ?? '';
        }
        $this->result($result, 0, '获取成功');
    }


    public function comobo()
    {
        $list = (new Promo())->field('id,title,descs,images,money')->where(['status' => 1, 'type' => 2, 'agentid' => 0])->select();
        $this->result($list, 0, '获取成功');
    }

    public function  riderauth()
    {
        return view();
    }

    public function pay()
    {
        return view();
    }

    public function aliypay()
    {
        $paymentid = $this->request->get('paymentid/d');
        $bdurl = $this->request->get('url') ?? 'other/baoming';
        $payment = (new Payment())->where(['paymentid' => $paymentid, 'paytype' => 3])->find();
        $payment = [
            'pay_title' => '报名订单支付',
            'payment_id' =>  $paymentid,
            'money' => $payment['money'],
            'ip' => $this->request->ip(),
            'params' => json_encode(['trade_type' => 'WAP', 'return_url' => url($bdurl, [], '', true)], true)
        ];
        $urls = '';
        $list = (new Alipay())->pay($payment);
        if ($list['status'] == true) {
            $url = http_build_query($list['data']['data']);
            $url = $list['data']['url'] . '?' . $url ?? '';
            $urls = $url;
        }
        return view('', ['money' => $payment['money'] ?? 0, 'url' => $urls, 'paymentid' => $paymentid, 'bdurl' => url($bdurl, [], '', true)]);
    }



    public function  ruchang()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $model = new Baoming();
            if (!empty($data['mobile']) && !empty($data['istrue']) && $data['istrue'] == 1) {
                $baoming = $model->where(['mobile' => $data['mobile'], 'status' => 2, 'type' => 2])->find();
                if (!empty($baoming)) {
                    $this->result([], 0, '获取成功，已经报名');
                }
                $this->result([], 1, '获取失败，未报名');
            }
            $validate = new Validate([
                'name' => 'require',
                'mobile' => 'require',
                'age' => 'require',
                'gongsi' => 'require',
                'zhiwei' => 'require',
                'yxhz' => 'require',
                'zsfxs' => 'require',
                'payment' => 'require|in:1,2'

            ], [
                'name.require' => '姓名不能为空',
                'mobile.require' => '电话不能为空',
                'age.require' => '年龄不能为空',
                'gongsi.require' => '公司不能为空',
                'zhiwei.require' => '职位不能为空',
                'yxhz.require' => '意向合作区域不能为空',
                'zsfxs.require' => '订购房型不能为空',
                'payment.require' =>  '支付方式不能为空',
                'payment.in' =>  '支付类型不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            if (empty($data['num'])) {
                $this->result([], 1, '费用办理选项不能为空');
            }
            if (!is_array($data['num'])) {
                $this->result([], 1, '费用办理选项数据错误');
            }
            $data['type'] = 2;
            $baoming = $model->where('mobile', $data['mobile'])->where('type', 2)->find();
            if (!empty($baoming) && $baoming['status'] == 2) {
                $this->result([], 2, '当前手机绑定用户已报名成功,无需重复提交');
            }
            $zscs = (new Config())->where('name', 'zshd2')->value('value');
            $zscs = json_decode($zscs, true) ?? [];
            //计算金额
            $total = 0;
            $product = '';
            foreach ($data['num'] as $k => &$nums) {
                $confignum = $zscs['param'][$k]['number'] ?? 0;
                if ($nums > 0 && ($nums >  $confignum || $confignum <= 0)) {
                    $this->result([], 1, '参会费用名额不足');
                }
                $total += $nums * ($zscs['param'][$k]['price'] ?? 0);
                if ($nums > 0) {
                    $product = $product . $zscs['param'][$k]['title'] . '*' . $nums . ' ';
                }
            }
            $data['products'] = json_encode($data['num'], true);
            $data['status'] = 1;
            $data['product'] = $product;
            $data['total'] = $total;
            $data['created'] = date('Y-m-d H:i:s');
            if ($total <= 0) {
                $this->result([], 1, '支付金额必须大于0');
            }
            switch ($data['payment']) {
                case '1':
                    if (empty($data['openid'])) {
                        $this->result([], 1, '请在微信打开页面并支付');
                    }
                    $ordersn = repayorder(new Payment());
                    $payment = [
                        'pay_title' => '报名订单支付',
                        'payment_id' =>  $ordersn,
                        'money' => $total,
                        'ip' => $this->request->ip(),
                        'params' => json_encode(['trade_type' => 'JSAPI_OFFICIAL', 'openid' => $data['openid']], true)
                    ];
                    $list = (new Wechat2())->pay($payment);
                    if ($list['status'] == true) {
                        if (!empty($baoming)) {
                            $res2 = $model->allowfield(true)->save($data, ['id' => $baoming['id']]);
                            $getid = $baoming['id'];
                        } else {
                            $res2 = $model->allowfield(true)->save($data);
                            $getid =  $model->id;
                        }
                        $res = (new Payment())->save(['user_id' => 0, 'money' => $data['total'], 'type' => 6, 'status' => 1, 'paymentid' => $ordersn, 'ordersn' => $getid]);
                        if ($res && $res2) {
                            $this->result($list['data'], 0, '获取参数成功');
                        } else {
                            $this->result([], 1, '获取失败,请重试');
                        }
                    } else {
                        $this->result([], 1, $list['msg'] ?? '获取失败');
                    }
                    break;
                case '2':
                    $ordersn = repayorder(new Payment());
                    $payment = [
                        'pay_title' => '报名订单支付',
                        'payment_id' =>  $ordersn,
                        'money' => $total,
                        'ip' => $this->request->ip(),
                        'params' => json_encode(['trade_type' => 'WAP', 'return_url' => url('other/ruchang', [], '', true)], true)
                    ];
                    $list = (new Alipay())->pay($payment);
                    if ($list['status'] == true) {
                        if (!empty($baoming)) {
                            $res2 = $model->allowfield(true)->save($data, ['id' => $baoming['id']]);
                            $getid = $baoming['id'];
                        } else {
                            $res2 = $model->allowfield(true)->save($data);
                            $getid =  $model->id;
                        }
                        $res = (new Payment())->save(['user_id' => 0, 'paytype' => 3, 'money' => $data['total'], 'type' => 6, 'status' => 1, 'paymentid' => $ordersn, 'ordersn' => $getid]);
                        if ($res && $res2) {
                            $url = http_build_query($list['data']['data']);
                            $url = $list['data']['url'] . '?' . $url ?? '';
                            $list['data']['url'] = $url;
                            $this->result($list['data'], 0, '获取成功');
                        } else {
                            $this->result([], 1, '获取失败,请重试');
                        }
                    }
                    break;

                default:
                    $this->result([], 1, '支付方式暂未开放');
                    break;
            }
        } else {
            $data = $this->request->get();
            //超过1分钟未支付取消
            $model = new Baoming();
            $baomings = $model->where(['status' => 1])->where('created', '<=', date('Y-m-d H:i:s', time() - 120))->select();
            foreach ($baomings as $baoming) {
                Db::startTrans();
                try {
                    $model->where(['status' => 1, 'id' => $baoming['id']])->update(['status' => 3]);
                    Db::commit();
                } catch (\Exception $e) {
                }
            }
            $share = [];
            $url = "https://" . Env('app.api_url') . url();
            $zscs = (new Config())->where('name', 'zshd2')->value('value');
            $zscs = json_decode($zscs, true) ?? [];
            try {
                $config = config('wechat1.');
                $app = Factory::officialAccount($config);
                $app->jssdk->setUrl($url);
                $res = $app->jssdk->buildConfig(array('updateAppMessageShareData', 'updateTimelineShareData'), false);
                $share = json_decode($res, true);
                if (!empty($data['code'])) {
                    $wxuser = $app->oauth->user();
                    if (!empty($wxuser['id'])) {
                        return view('', ['share' => $share, 'openid' => $wxuser['id'], 'zscs' => $zscs]);
                    }
                }
            } catch (\Exception $e) {
            }
            return view('', ['share' => $share, 'zscs' => $zscs]);
        }
    }


    public function  baoming()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $model = new Baoming();
            if (!empty($data['mobile']) && !empty($data['istrue']) && $data['istrue'] == 1) {
                $baoming = $model->where(['mobile' => $data['mobile'], 'status' => 2])->find();
                if (!empty($baoming)) {
                    $this->result([], 0, '获取成功，已经报名');
                }
                $this->result([], 1, '获取失败，未报名');
            }
            $validate = new Validate([
                'name' => 'require',
                'mobile' => 'require',
                'age' => 'require',
                'gongsi' => 'require',
                'zhiwei' => 'require',
                'yxhz' => 'require',
                'payment' => 'require|in:1,2'

            ], [
                'name.require' => '姓名不能为空',
                'mobile.require' => '电话不能为空',
                'age.require' => '年龄不能为空',
                'gongsi.require' => '公司不能为空',
                'zhiwei.require' => '职位不能为空',
                'yxhz.require' => '意向合作区域不能为空',
                'payment.require' =>  '支付方式不能为空',
                'payment.in' =>  '支付类型不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            if (empty($data['num'])) {
                $this->result([], 1, '费用办理选项不能为空');
            }
            if (!is_array($data['num'])) {
                $this->result([], 1, '费用办理选项数据错误');
            }
            // $baoming = $model->where('mobile', $data['mobile'])->find();
            // if (!empty($baoming) && $baoming['status'] == 2) {
            //     //$this->result([], 2, '当前手机绑定用户已报名成功,无需重复提交');
            // }
            $zscs = Redis::get('zshdconfig');
            if (!$zscs) {
                $zscs = (new Config())->where('name', 'zshd')->value('value');
                //$zscs = Redis::set('zshdconfig', $zscs);
            }
            $zscs = json_decode($zscs, true) ?? [];
            //计算金额
            $total = 0;
            $product = '';
            foreach ($data['num'] as $k => &$nums) {
                $confignum = $zscs['param'][$k]['number'] ?? 0;
                if ($nums > 0 && ($nums >  $confignum || $confignum <= 0)) {
                    $this->result([], 1, '参会费用名额不足');
                }
                $total += $nums * ($zscs['param'][$k]['price'] ?? 0);
                if ($nums > 0) {
                    $product = $product . $zscs['param'][$k]['title'] . '*' . $nums . ' ';
                }
                //$zscs['param'][$k]['number'] -= $nums;
            }
            $data['products'] = json_encode($data['num'], true);
            $data['status'] = 1;
            $data['product'] = $product;
            $data['total'] = $total;
            $data['created'] = date('Y-m-d H:i:s');
            if ($total <= 0) {
                $data['payment'] = 0;
                $data['status'] = 2;
                if (!empty($baoming)) {
                    $res = $model->allowfield(true)->save($data, ['id' => $baoming['id']]);
                } else {
                    $res = $model->allowfield(true)->save($data);
                }
                if ($res) {
                    $this->result([], 2, '预约成功');
                }
                $this->result([], 1, '预约失败，请重试');
            }
            switch ($data['payment']) {
                case '1':
                    if (empty($data['openid'])) {
                        $this->result([], 1, '请在微信打开页面并支付');
                    }
                    $ordersn = repayorder(new Payment());
                    $payment = [
                        'pay_title' => '报名订单支付',
                        'payment_id' =>  $ordersn,
                        'money' => $total,
                        'ip' => $this->request->ip(),
                        'params' => json_encode(['trade_type' => 'JSAPI_OFFICIAL', 'openid' => $data['openid']], true)
                    ];
                    $list = (new Wechat2())->pay($payment);
                    if ($list['status'] == true) {
                        if (!empty($baoming)) {
                            $res2 = $model->allowfield(true)->save($data, ['id' => $baoming['id']]);
                            $getid = $baoming['id'];
                        } else {
                            $res2 = $model->allowfield(true)->save($data);
                            $getid =  $model->id;
                        }
                        if ($res2) {
                            if (!empty($baoming) && $baoming['status'] == 1) {
                                $products = json_decode($baoming['products'], true);
                                foreach ($products as $ks => $vs) {
                                    if ($vs > 0) {
                                        //$zscs['param'][$ks]['number'] += $vs;
                                    }
                                }
                            }
                            Redis::set('zshdconfig', json_encode($zscs, true));
                            (new Config())->where('name', 'zshd')->update(['value' => json_encode($zscs, true)]);
                        }
                        $res = (new Payment())->save(['user_id' => 0, 'money' => $data['total'], 'type' => 6, 'status' => 1, 'paymentid' => $ordersn, 'ordersn' => $getid]);
                        if ($res && $res2) {
                            $this->result($list['data'], 0, '获取参数成功');
                        } else {
                            $this->result([], 1, '获取失败,请重试');
                        }
                    } else {
                        $this->result([], 1, $list['msg'] ?? '获取失败');
                    }
                    break;
                case '2':
                    $ordersn = repayorder(new Payment());
                    $payment = [
                        'pay_title' => '报名订单支付',
                        'payment_id' =>  $ordersn,
                        'money' => $total,
                        'ip' => $this->request->ip(),
                        'params' => json_encode(['trade_type' => 'WAP', 'return_url' => url('other/baoming', [], '', true)], true)
                    ];
                    $list = (new Alipay())->pay($payment);
                    if ($list['status'] == true) {
                        if (!empty($baoming)) {
                            $res2 = $model->allowfield(true)->save($data, ['id' => $baoming['id']]);
                            $getid = $baoming['id'];
                        } else {
                            $res2 = $model->allowfield(true)->save($data);
                            $getid =  $model->id;
                        }
                        if ($res2) {
                            if (!empty($baoming) && $baoming['status'] == 1) {
                                $products = json_decode($baoming['products'], true);
                                foreach ($products as $ks => $vs) {
                                    if ($vs > 0) {
                                        $zscs['param'][$ks]['number'] += $vs;
                                    }
                                }
                            }
                            Redis::set('zshdconfig', json_encode($zscs, true));
                            (new Config())->where('name', 'zshd')->update(['value' => json_encode($zscs, true)]);
                        }
                        $res = (new Payment())->save(['user_id' => 0, 'paytype' => 3, 'money' => $data['total'], 'type' => 6, 'status' => 1, 'paymentid' => $ordersn, 'ordersn' => $getid]);
                        if ($res && $res2) {
                            // dump($list['data']['data']['biz_content']);
                            // $list['data']['data']['biz_content'] = json_decode($list['data']['data']['biz_content'],true) ?? [];
                            $url = http_build_query($list['data']['data']);
                            $url = $list['data']['url'] . '?' . $url ?? '';
                            $list['data']['url'] = $url;
                            $this->result($list['data'], 0, '获取成功');
                        } else {
                            $this->result([], 1, '获取失败,请重试');
                        }
                    }
                    break;

                default:
                    $this->result([], 1, '支付方式暂未开放');
                    break;
            }
        } else {
            $data = $this->request->get();
            //超过1分钟未支付取消
            $model = new Baoming();
            // $baomings = $model->where(['status' => 1])->where('created', '<=', date('Y-m-d H:i:s', time() - 60))->select();
            // $zscs = Redis::get('zshdconfig');
            // if (!$zscs) {
            //     $zscs = (new Config())->where('name', 'zshd')->value('value');
            //     $zscs = Redis::set('zshdconfig', $zscs);
            // }
            // $zscs = json_decode($zscs, true) ?? [];
            // foreach ($baomings as $baoming) {
            //     $products = json_decode($baoming['products'], true);
            //     foreach ($products as $ks => $vs) {
            //         if ($vs > 0) {
            //             $zscs['param'][$ks]['number'] += $vs;
            //         }
            //     }
            //     Db::startTrans();
            //     try {
            //         (new Config())->where('name', 'zshd')->update(['value' => json_encode($zscs, true)]);
            //         $model->where(['status' => 1, 'id' => $baoming['id']])->update(['status' => 3]);
            //         Db::commit();
            //     } catch (\Exception $e) {
            //     }
            //     Redis::set('zshdconfig', json_encode($zscs, true));
            // }
            $share = [];
            $url = "https://" . Env('app.api_url') . url();
            $zscs = (new Config())->where('name', 'zshd')->value('value');
            $zscs = json_decode($zscs, true) ?? [];
            // if (!is_array($zscs)) {
            //     $zscs = [];
            // }
            try {
                $config = config('wechat1.');
                $app = Factory::officialAccount($config);
                $app->jssdk->setUrl($url);
                $res = $app->jssdk->buildConfig(array('updateAppMessageShareData', 'updateTimelineShareData'), false);
                $share = json_decode($res, true);
                if (!empty($data['code'])) {
                    $wxuser = $app->oauth->user();
                    if (!empty($wxuser['id'])) {
                        return view('', ['share' => $share, 'openid' => $wxuser['id'], 'zscs' => $zscs]);
                    }
                }
            } catch (\Exception $e) {
            }
            return view('', ['share' => $share, 'zscs' => $zscs]);
        }
    }

    public function  bauth()
    {
        $data = $this->request->get();
        $validate = new Validate([
            'code' => 'require',
        ], [
            'code.require' => 'code不能为空',
        ]);
        if (!$validate->check($data)) {
            return $validate->getError();
        }
        $config = config('wechat1.');
        try {
            $app = Factory::officialAccount($config);
            $wxuser = $app->oauth->user();
            if (!empty($wxuser['id'])) {
                $this->result(['openid' => $wxuser['id']], 0, '获取成功');
            }
        } catch (\Exception $e) {
            $this->result([], 1, '获取失败');
        }
    }

    public function checkclear()
    {
        $data = $this->request->get();
        $validate = new Validate([
            'streetid' => 'require'
        ], [
            'streetid.require' => '街道信息不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $data['lat'] = $data['lat'] ?? 0;
        $data['lng'] = $data['lng'] ?? 0;
        $address = getlatlon($data['lat'], $data['lng'], 3);
        if (empty($address['agentid'])) {
            $address = getdrees($data['streetid'], 3);
        }
        //判断当前区域是否有代理
        $agentid = $address['agentid'] ?? 0;
        if (empty($agentid)) {
            $this->result([], 1, '您所定位的区域暂未开通无法为您提供服务，请重新设置车辆位置');
        }
        //查一下是否全国代理
        $isall = (new AgentArea())->where(['type' => 1, 'agentid' => $agentid])->find();
        if (!empty($isall)) {
            $this->result([], 1, '您所定位的区域暂未开通无法为您提供服务，请重新设置车辆位置');
        }
        //查询是否有街道服务人员
        $RiderStreet = (new RiderStreet())->where(['status' => 2, 'agentid' => $agentid])->column('riderid');
        if (count($RiderStreet) <= 0) {
            $this->result([], 1, '您所定位的区域暂无服务人员可以为您提供服务，请重新设置车辆位置');
        }
        // $car = (new Car())->where('user_id', $this->request->user_id)->order('is_default desc')->find();
        // if (empty($car)) {
        //     $this->result([], 2, '您未设置车辆信息，请添加车辆信息后继续');
        // }
        $this->result([], 0, '当前区域可服务');
    }

    public function  riderauth2()
    {
        $data = $this->request->get();
        $validate = new Validate([
            'code' => 'require',
            'mobile' => 'require'
        ], [
            'code.require' => 'code不能为空',
            'mobile.require' => '师傅账号不能为空'
        ]);
        if (!$validate->check($data)) {
            return $validate->getError();
        }
        $user = (new Riderlist())->where(['mobile' => $data['mobile']])->find();
        if (empty($user)) {
            return view(null, ['list' => ['status' => 1, 'info' => '师傅账号不存在,请确保手机号码正确!']]);
        }
        $config = config('wechat1.');
        $appid = config('wechat.')['app_id'] ?? '';
        //进行通知
        $data = [
            'first' => [
                'value' => '新订单通知，请前往处理订单'
            ],
            'keyword1' => [
                'value' => time()
            ],
            'keyword2' => [
                'value' => rand(100, 9999)
            ],
            'keyword3' => [
                'value' => date('Y-m-d H:i:s')
            ],
            'remark' => [
                'value' => '本通知为订阅成功后发送的测试消息!'
            ],
        ];
        try {
            $app = Factory::officialAccount($config);
            $wxuser = $app->oauth->user();
            if (!empty($wxuser['id'])) {
                $wuser = $app->user->get($wxuser['id']);
                if (empty($wuser['subscribe']) || $wuser['subscribe'] != 1) {
                    return view(null, ['list' => ['status' => 1, 'info' => '授权通知前请先关注公众号!']]);
                }
                if ($user['openid'] == $wxuser['id']) {
                    wechatmessage($wxuser['id'], 'Ir0bvb7_sfvd0U6F8u97yXQvkJfOc6Vz-Qk_ljboHU4', $data, $appid, '/pages/horseman/index');
                    return view(null, ['list' => ['status' => 1, 'info' => '您已授权成功!']]);
                }
                $res = (new Riderlist())->where(['id' => $user['id']])->update(['openid' => $wxuser['id']]);
                if (!$res) {
                    return view(null, ['list' => ['status' => 1, 'info' => '授权失败!']]);
                }
                wechatmessage($wxuser['id'], 'Ir0bvb7_sfvd0U6F8u97yXQvkJfOc6Vz-Qk_ljboHU4', $data, $appid, '/pages/horseman/index');
                return view(null, ['list' => ['status' => 0, 'info' => '授权成功!']]);
            }
        } catch (\Exception $e) {
            return view(null, ['list' => ['status' => 1, 'info' => '授权失败!']]);
            // return $e->getMessage();
        }
    }

    public function getconfig()
    {
        $name = $this->request->get('name/s', 0);
        $list = (new Config())->where('name', $name)->value('value') ?? '';
        $this->result($list, 0, '获取成功');
    }


    public function street()
    {
        $areacode = $this->request->get('areacode/d', 0);
        $list = (new Region())->where('area_code', $areacode)->where(['level' => 4])->select();
        $this->result($list, 0, '获取成功');
    }

    public function annous()
    {
        $streetid = $this->request->get('streetid/d', 0);
        $data['lat'] = $this->request->get('lat') ?? 0;
        $data['lng'] = $this->request->get('lng') ?? 0;
        $agentid = getlatlon($data['lat'], $data['lng'], 1);
        if (empty($agentid)) {
            $agentid = getdrees($streetid, 1);
        }
        $list = (new Annous())->where(['agentid' => $agentid])->order('id desc')->field('id,title,types,content')->find();
        if (empty($list)) {
            $list = (new Annous())->where(['agentid' => 0])->order('id desc')->field('id,title,types,content')->find();
        }
        $this->result($list, 0, '获取成功');
    }

    public function oss()
    {
        if ($this->request->isPost()) {
            if (Env::get('aliyun.open')) {
                $file =  $_FILES['file'] ?? '';
                if (empty($file)) {
                    $this->result([], 1, '请选择上传图片');
                }
                $oss = new Oss();
                $oss->setUploadType('ram');
                $url = $oss->uploadPostFile($file, 'duangduang/' . date('Y-m-d'));
                $this->result($url, 0, '获取成功');
                $result = [];
                try {
                    $result = (new Oss())->getCredentials();
                    $result['regionId'] = Env::get('aliyun.regionId');
                    $result['bucket'] = Env::get('aliyun.bucket');
                    $result['endpoint'] = Env::get('aliyun.endpoint');
                } catch (\Exception $e) {
                    $this->result([], 1, $e->getMessage());
                }
                $this->result($result, 0, '获取成功');
            } else {
                $file = request()->file('file');
                $path =  $_SERVER['DOCUMENT_ROOT'] . "/uploads/";
                $info = $file->validate(['ext' => 'jpg,png,gif,jpeg'])
                    ->move($path);
                if (!$info) {
                    $this->result([], 1, $file->getError());
                } else {
                    $file_edit = $info->getInfo();
                    $url = './uploads' . '/' . date("Ymd") . '/' . $info->getfileName();
                    if ($file_edit['size'] > 204800) { // 大于100K的图片进行处理
                        // 获取上传的图片，进行图片压缩
                        $image = \think\Image::open($info);
                        // 保存图片的路径处理
                        $image->thumb(1400, 1400)->save($url);
                    }
                    $url = url($url, '', '', false);
                    $url = "https://" . Env('app.api_url') . $url;
                    $this->result($url, 0, '获取成功');
                }
            }
        }
    }

    //高德接口
    public function getstreet()
    {
        $key = env('map.key');
        if ($this->request->isGet()) {
            $data = $this->request->get();
            $validate = new Validate([
                'lat' => 'require',
                'lng' => 'require',
            ], [
                'lat.require' => '纬度必须填写',
                'lng.require' => '经度必须填写',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $url = 'https://restapi.amap.com/v3/geocode/regeo';
            $res = api_curl($url, ['location' => $data['lng'] . ',' . $data['lat'], 'key' => $key, 'extensions' => 'all']);
            Log::write($data, 'getstreet');
            if ($res['status'] == 1) {
                if (empty($res['regeocode']['addressComponent'])) {
                    $this->result([], 1, '请求失败,请重试');
                }
                $results = $res['regeocode']['addressComponent'];
                //街道查不到重新请求
                if (empty($results['township'])) {
                    $data['lng'] = floor($data['lng'] * 10000) / 10000;
                    $data['lat'] = floor($data['lat'] * 10000) / 10000;
                    $res = api_curl($url, ['location' => $data['lng'] . ',' . $data['lat'], 'key' => $key, 'extensions' => 'all']);
                    if ($res['status'] == 1) {
                        if (empty($res['regeocode']['addressComponent'])) {
                            $this->result([], 1, '请求失败,请重试');
                        }
                        $results = $res['regeocode']['addressComponent'];
                    }
                }
                $add = $res['regeocode']['aois'][0]['name'] ?? '';
                if (empty($add)) {
                    $add = $res['regeocode']['pois'][0]['name'] ?? '';
                }
                $resuls = [
                    "adcode" => !empty($results['adcode']) ? $results['adcode'] : 0,
                    "province" => !empty($results['province']) ? $results['province'] : '未知省份',
                    "city" => !empty($results['city']) ? $results['city'] : '直辖市',
                    "district" => !empty($results['district']) ? $results['district'] : '未知区域',
                    "street" => 0,
                    "street_title" => !empty($results['township']) ? $results['township'] : '未知街道',
                    'address' => $add ?? '',
                    'formatted_address' => $res['regeocode']['formatted_address'] ?? ''
                ];
                $results['towncode'] = !empty($results['towncode']) ? $results['towncode'] : 0;
                $resuls['city'] = empty($resuls['city']) ? $resuls['province'] : $resuls['city'];
                $street_id = (new Region())
                    ->where(['level' => 4])
                    ->where('area_code', $resuls['adcode'])
                    ->where('name|remark', 'like', '%' . $resuls['street_title'] . '%')->find();
                //长名字查找不到 缩减名字查找
                $township = mb_substr($resuls['street_title'], 0, 2, 'utf-8');
                if (empty($street_id['id'])) {
                    $street_id = (new Region())
                        ->where(['level' => 4])
                        ->where('area_code', $resuls['adcode'])
                        ->where('name|remark', 'like', '%' . $township . '%')->find();
                }
                //通过名字查找不到街道再通过编号查找
                if (empty($street_id['id'])) {
                    $street_id = (new Region())
                        ->where(['level' => 4])
                        ->where('area_code', $resuls['adcode'])
                        ->where('code', substr($results['towncode'] ?? 0, 0, 9))->find();
                }
                $resuls['street'] = $street_id['id'] ?? 0;
                $resuls['street_title'] = $street_id['name'] ?? $resuls['street_title'];
                // //插入街道
                if (empty($resuls['street']) && !empty($resuls['adcode'])) {
                    $insertregion = (new Region())->where(['level' => 3, 'area_code' => $resuls['adcode']])->value('id');
                    if ($insertregion > 0) {
                        $resuls['street'] = (new Region())->insertGetId(
                            [
                                'parent_id' => $insertregion,
                                'level' => 4,
                                'name' => $resuls['street_title'],
                                'area_code' => $resuls['adcode'],
                                'code' => $resuls['adcode'] * 1000
                            ]
                        );
                    }
                }
                Log::write($resuls, 'getstreet');
                $this->result($resuls, 0, '获取成功');
            } else {
                $this->result([], 1, '请求失败');
            }
        } else {
            $this->result([], 0, ['key' => $key]);
        }
    }

    public function addressjson()
    {
        $addressjsonredis = 'addressjsonredis';
        $haveaddress = Redis::get($addressjsonredis);
        if ($haveaddress) {
            $result = unserialize($haveaddress);
        } else {
            $region = (new Region())->field('name as label,area_code as value,id,parent_id,level')->where(['level' => [1, 2, 3]])->select();
            $resultson = [];
            $results = [];
            $result = [];
            foreach ($region as $regions) {
                if ($regions['level'] == 3) {
                    $resultson[$regions['parent_id']][] = [
                        'label' => $regions['label'],
                        'value' => $regions['value']
                    ];
                }
            }
            foreach ($region as $regions) {
                if ($regions['level'] == 2) {
                    $results[$regions['parent_id']][] = [
                        'label' => $regions['label'],
                        'value' => $regions['value'],
                        'children' => $resultson[$regions['id']] ?? []
                    ];
                }
            }
            foreach ($region as $regions) {
                if ($regions['level'] == 1) {
                    $result[] = [
                        'label' => $regions['label'],
                        'value' => $regions['value'],
                        'children' => $results[$regions['id']] ?? []
                    ];
                }
            }
            Redis::setex($addressjsonredis, 60 * 60 * 3, serialize($result));
        }
        return json($result);
    }

    public function cate()
    {
        $list =  (new Cate())->order(['sort' => 'desc', 'id' => 'desc'])->where(['isshow' => 1])->field('id,name')->select();
        $this->result($list, 0, '获取成功');
    }

    public function product()
    {
        $streetid = $this->request->get('streetid/d', 0);
        if (empty($streetid)) {
            $this->result('', 0, '获取成功');
        }
        $cate = $this->request->get('cate/d', 0);
        $data['lat'] = $this->request->get('lat') ?? 0;
        $data['lng'] = $this->request->get('lng') ?? 0;
        $agentid = getlatlon($data['lat'], $data['lng'], 1);
        if (empty($agentid)) {
            $agentid = getdrees($streetid, 1);
        }

        //获取街道区域代理ID
        if (empty($agentid)) {
            $this->result('', 0, '获取成功');
        }
        $list =  (new Product())
            ->where(['isdel' => 1, 'isshow' => 1, 'agentid' => $agentid])
            ->field('id,title,images,price,price1,price2,descs,iskey');
        if (!empty($cate)) {
            $list = $list->where('cate', $cate);
        }
        $list = $list->order(['sales' => 'desc', 'sort' => 'desc'])->select();
        $this->result($list, 0, '获取成功');
    }

    //支付回调结果
    public function callback()
    {
        $type = input('type/d');
        if (!empty($type) && $type == 2) {
            $result = (new Douyin())->callback();
        } elseif (!empty($type) && $type == 3) {
            $result = (new Alipay())->callback();
        } else {
            $result = (new Wechat())->callback();
        }
        if ($result['msg'] == 'success') {
            return 'SUCCESS';
        }
        return false;
    }

    //微信取消订单回调结果
    public function callback2()
    {
        $result = (new Wechat())->callback2();
        Log::write($result, 'refund');
        if ($result['msg'] == 'success') {
            return 'SUCCESS';
        }
        return false;
    }

    //微信取消订单回调结果
    public function callback3()
    {
        $result = (new Douyin())->callback2();
        Log::write($result, 'refund');
        if ($result['msg'] == 'success') {
            return 'SUCCESS';
        }
        return false;
    }
}
